var Role = function () {

    var basePath = ROOT_PATH + 'upms/role/',
        pagePath = ROOT_PATH + 'pages/upms/role/',
        $roleGrid = null,
        $dialog = null;

    function initGrid(gridId) {
        var gid = gridId || '#grid-data';
        $roleGrid = BsGridUtil.initListGrid({
            gridId: gid,
            url: basePath + "list",
            toolbar: '#roleTb',                //工具按钮用哪个容器
            columns: [
                {field: 'selectItem', checkbox:true},
                {field:"id",title:"id"},
                {field:"roleName",title:"角色名"},
                {field:"remark",title:"备注"},
                {field:"status",title:"状态",formatter:FormUtils.enumFormatter},
                {field:"optFormatter",title:"操作", formatter: operateFormatter}
                ],
        });
    }

    function operateFormatter(value, row, index) {//赋予的参数
        if ($('#editRolePermission').length > 0 && $('#getResourcesPermission').length > 0) {
            return '<a href="javascript:Role.editRole(' + row.id + ')" class="btn btn-xs btn-primary"><span class="glyphicon glyphicon-pencil"></span>编辑</a>' + '&nbsp;'+
                '<a href="javascript:Role.assignResource(' + row.id + ')" class="btn btn-xs btn-primary"><span class="fa fa-repeat"></span>分配权限</a>';
        } else if ($('#editRolePermission').length == 0 && $('#getResourcesPermission').length > 0) {
            return '<a href="javascript:Role.assignResource(' + row.id + ')" class="btn btn-xs btn-primary"><span class=\'glyphicon glyphicon-share-alt\'><span class="fa fa-repeat"></span>分配权限</a>';
        } else if ($('#editRolePermission').length > 0 && $('#getResourcesPermission').length == 0) {
            return '<a href="javascript:Role.editRole(' + row.id + ')" class="btn btn-xs btn-primary"><span class="glyphicon glyphicon-pencil">编辑</a>';
        } else {
            return null;
        }
    }

    /**
     * 给角色分配权限
     * @param roleId 角色id
     */
    function assignResource(roleId) {
        var zTree, $dialog;
        /**
         * 渲染树
         * @param resourceIds 该角色已选的资源id
         */
        function renderTree(resourceIds) {
            var treeSetting = {
                treeId: '#resourceTree',
                async: {
                    url: ROOT_PATH + 'upms/resource/listByUser',
                },
                callback: {
                    extendsAsyncSuccess: function (_zTree) {
                        $.each(resourceIds, function (i, resourceId) {
                            var node = _zTree.getNodeByParam("id", resourceId);

                            if (node) {
                                _zTree.checkNode(node);
                            }

                        });
                    }
                }
            };
            zTree = Tree.getTree(treeSetting);
        }

        /**
         * 弹出框打开选择页面
         */
        function openModal(data) {
            $.Get(pagePath + 'role-auth.html', function (page) {
                $dialog = $(page);
                $dialog.modal().on('shown.bs.modal', function (e) {
                    renderTree(data);
                    bindAssignEvent();
                });
            });
        }

        /**
         * 绑定提交事件
         */
        function bindAssignEvent() {
            $dialog.find('button.btn-primary').off("click").on("click", function () {
                var nodes = zTree.getCheckedNodes();
                if (nodes && nodes.length > 0) {
                    var resourceIds = [];
                    $.each(nodes, function (i, node) {
                        resourceIds.push(node.id);
                    })
                    setResources(resourceIds);
                } else {
                    Dialog.warning("请选择资源");
                }
            });
            $dialog.modal().on("hidden.bs.modal", function () {
                $dialog.remove();
            });
        }

        /**
         * 保存选择的资源
         */
        function setResources(resourceIds) {
            $.Ajax({
                url: basePath + "setResources",
                method:"post",
                data: {resourceIds: resourceIds, roleId: roleId},
                container: $dialog,
                success: function () {
                    $dialog.modal('hide');
                    Dialog.success("分配权限成功");
                }
            });
        }

        $.Get(basePath + 'getResources', {id: roleId}, function (data) {
            openModal(data);
        });

    }

    /**
     * 编辑
     */
    function editRole(id) {
        $.Get(pagePath + 'role-edit.html', function (page) {
            $dialog = $(page);
            var $form = $dialog.find('form:first');
            $dialog.modal().on("shown.bs.modal", function () {
                $.Get(basePath + 'get', {id: id}, function (data) {
                    if (data) {
                        FormUtils.setValues($form, data.data);
                    } else {
                        Dialog.error("角色不存在");
                    }
                });
                validate($form);
            })
        })
    }


    /**
     * 创建角色
     */
    function createRole() {
        $.Get(pagePath + 'role-create.html', function (page) {
            $dialog = $(page);
            var $form = $dialog.find('form:first');
            $dialog.modal().on("shown.bs.modal", function () {
                validate($form);
            })
        });
    }

    function validate(formId) {
        FormUtils.validate(formId, {
            rules: {
                roleName: {
                    maxlength: 20,
                    required: true
                },
                remark: {
                    maxlength: 50
                },
            },
            messages: {
                roleName: {
                    required: "角色名称不可为空",
                    maxlength: '最多只能输入20个字符',
                },
                remark: {
                    maxlength: "备注最多允许输入50个字符"
                },
            },
            submitHandler: function () {
                $.Ajax({
                    url: $(formId).attr("action"),
                    data: FormUtils.getFormObj(formId),
                    container: formId,
                    success: function () {
                        $dialog.modal('hide');
                        Dialog.success("操作成功");
                        $roleGrid.bootstrapTable("refresh");
                    }
                });
            }
        });
    }

    /**
     * 初始化一个供选择的grid
     * @param gridId
     * @param opts
     * @returns {jQuery}
     */
    function initGrid4Choose(gridId, opts) {
        var defaults = {
            gridId: gridId,
            singleSelect:false,
            toolbar:"",
            url: basePath + 'list',
            showRefresh:false,
            columns: [
                {field: 'selectItem', checkbox:true},
                {field: 'id', title: 'id', visible: false},
                {field: 'roleName', title: '角色名称'},
                {field: 'remark', title: '备注'}
            ],
        };
        opts = $.extend(true, defaults, opts);
        return BsGridUtil.initListGrid(opts);
    }

    /**
     * 删除角色
     */
    function delRole() {
        var roleIds = $roleGrid.bootstrapTable("getSelections");
        if (roleIds.length > 0){
            $.Get(basePath + "delRole",{id:roleIds[0].id},function (data) {
                $roleGrid.bootstrapTable("refresh");
                Dialog.success(data.data);
            })
        }
    }

    return {

        /**
         * 初始化数据表格
         * @param gridId
         */
        initGrid: initGrid,
        /**
         * 添加角色
         */
        createRole: createRole,
        /**
         * 查看详情
         */
        editRole: editRole,
        /**
         * 给角色分配资源
         */
        assignResource: assignResource,
        /**
         * 初始化角色grid
         */
        initGrid4Choose:initGrid4Choose,
        /**
         * 删除角色
         */
        delRole:delRole
    }
}();